﻿/***************************************************
Copyright (C) 2012 Alexander Forselius

Permission is hereby granted, free of charge, to any person obtaining a copy of this 
software and associated documentation files (the "Software"), to deal in the Software
 without restriction, including without limitation the rights to use, copy, modify, merge,
 publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons 
 to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or 
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using CefSharp;

namespace Bungalow
{


    public partial class WebApp : UserControl, IApp, CefSharp.IBeforeResourceLoad, CefSharp.IBeforeMenu
    {
        public Bungalow Host { get; set; }
        public static CefSharp.WinForms.WebView CurrentApp;
        private Dictionary<String, Image> appIcon = new Dictionary<string, Image>();
        public Dictionary<string, Image> AppIcon
        {
            get
            {
                return appIcon;
            }
        }
        public class ResourceLoadEventArgs {
            public WebApp App { get; set; }
            public CefSharp.IRequestResponse Request { get; set; }
            public bool Cancel { get; set; }
        }
       
        public delegate void ResourceLoadEventHandler(object esender, ResourceLoadEventArgs e);
        public ResourceLoadEventHandler StartDownloadResource { get; set; }

        public void HandleBeforeResourceLoad(CefSharp.IWebBrowser browserControl, CefSharp.IRequestResponse requestResponse)
        {
            if (requestResponse.Request.Url.StartsWith("spotify:") || requestResponse.Request.Url.StartsWith("bungalow:"))
            {
                
          
                 if (StartDownloadResource != null)
                {
                    ResourceLoadEventArgs args = new ResourceLoadEventArgs();
                    args.App = this;
                    args.Request = requestResponse;
                    this.Host.Invoke(new Action(() => StartDownloadResource(this, args)));
                    if (args.Cancel)
                        requestResponse.Cancel();
                }
            }
        }
        public bool Navigate(Uri uri)
        {
            if (uri.ToString().StartsWith("bungalow:app:"))
            {



                browser.Load("javascript:__argumentsChanged('" + uri.ToString() + "')");
                return true;
            }
            else
            {
                return false;
            }
        }
       
        public String Title
        {
            get
            {
                return this.title;
            }
        }
        Timer firstLoad = new Timer();
        public WebApp(string name, Bungalow host)
        {
            this.Namespace = name;
            this.title = name;
            InitializeComponent();
            firstLoad.Tick += new EventHandler(firstLoad_Tick);
            CefSharp.BrowserSettings browserSettings = new CefSharp.BrowserSettings();
            
            browserSettings.WebSecurityDisabled = true;
            browser = new CefSharp.WinForms.WebView("http://www.svt.se", browserSettings);
        
            
            browser.BeforeResourceLoadHandler = this;
            browser.BeforeMenuHandler = this;
            ContextMenu menu = new System.Windows.Forms.ContextMenu();

            MenuItem mnu_inspect = new MenuItem("Show Inspector");
            MenuItem mnu_refresh = new MenuItem("Reload application");
            menu.MenuItems.Add(mnu_inspect);
            mnu_inspect.Click += new EventHandler(mnu_inspect_Click);
            mnu_refresh.Click +=new EventHandler(mnu_refresh_Click);
            menu.MenuItems.Add(mnu_refresh);
            browser.ContextMenu = menu;

            browser.PropertyChanged += new PropertyChangedEventHandler(browser_PropertyChanged);
            this.Host = host;
            this.TestSchemeLoadActivated += new EventHandler(WebApp_TestSchemeLoadActivated);
            browser.Dock = DockStyle.Fill;
            this.Controls.Add(browser);

            this.UrlActivated += new Action<object, string>(WebApp_UrlActivated);
          
        }

        void mnu_inspect_Click(object sender, EventArgs e)
        {
            browser.ShowDevTools();
        }

        void WebApp_UrlActivated(object arg1, string arg2)
        {
          
        }

        void WebApp_TestSchemeLoadActivated(object sender, EventArgs e)
        {
            
        }

        void browser_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Address")
            {
                

            }
        }

        void mnu_refresh_Click(object sender, EventArgs e)
        {
            browser.Reload();
        }
        string path = "";
        void firstLoad_Tick(object sender, EventArgs e)
        {
            if (browser.IsBrowserInitialized)
            {
                browser.Load(path);
                firstLoad.Stop();
            }
        }
        public Uri PlayNext()
        {
            return new Uri("spotify:underfined");
        }
        CefSharp.WinForms.WebView browser;
        private string title;
        private void WebApp_Load(object sender, EventArgs e)
        {
       
        }
    
        public void  Save()
        {
 	        
        }

        public void  Save(string fileName)
        {
 	   
        }

        public bool isSaved
        {
            get;
            set;
        }

        public void  LoadFile(string fileName)
        {
            path = fileName;
            if (browser.IsBrowserInitialized)
            {

                browser.Load(fileName);
            }
            else
            {
                firstLoad.Start();
            }
        }

        public string  FileName
        {
            get;
            set;
        }
        public void Init(String _namespace)
        {
        }
        public bool Close()
        {
            return true;
        }
        public String Namespace
        {
            get;
            set;
        }


        public event EventHandler BackActivated;

        public event EventHandler CopyActivated;

        public event EventHandler CutActivated;

        public event EventHandler DeleteActivated;

        public void DisplayOutput(string output)
        {
            
        }

        public object EvaluateScript(string script)
        {
            return browser.EvaluateScript(script);
        }

        public void ExecuteScript(string script)
        {
            browser.ExecuteScript(script);
        }

        public event EventHandler ExitActivated;

        public event EventHandler ForwardActivated;

        public event EventHandler PasteActivated;

        public event EventHandler RedoActivated;

        public event EventHandler SelectAllActivated;

        public void SetAddress(string address)
        {
     
            
        }

        public void SetCanGoBack(bool can_go_back)
        {
            
        }

        public void SetCanGoForward(bool can_go_forward)
        {
            
        }

        public void SetIsLoading(bool is_loading)
        {
            
        }

        public void SetTitle(string title)
        {
            
        }

        public event EventHandler TestBindActivated;

        public event EventHandler TestConsoleMessageActivated;

        public event EventHandler TestEvaluateScriptActivated;

        public event EventHandler TestExecuteScriptActivated;

        public event EventHandler TestPopupActivated;

        public event EventHandler TestResourceLoadActivated;

        public event EventHandler TestSchemeLoadActivated;

        public event EventHandler TestTooltipActivated;

        public event EventHandler UndoActivated;

        public event Action<object, string> UrlActivated;


        object IApp.ExecuteScript(string script)
        {
           return browser.EvaluateScript(script);
           
        }

        public bool HandleBeforeMenu()
        {
            return true;
        }
    }
}
